/*
 * wireless.h
 *
 * Created: 2013/12/19 15:09:55
 *  Author: alivehex
 */ 


#ifndef WIRELESS_H_
#define WIRELESS_H_

#include "hardware.h"
#include "gpio.h"

#define RF_DEFAULT_CHANNEL		2
#define RF_CACHE_SIZEB			32

//typedef struct {
//	union {
//		uint16_t word[2];
//		char byte[4];
//	} header;
//	uint16_t index;		// command index
//	uint16_t value0;	// argument1
//	uint16_t value1;	// argument2
//} rf_ctrl_package_t;

// rfDataRate = 0(1Mbps), 1(2Mbps), 2(250Kpbs)
// rfPowerLevel = 0(Min) - 3(Max)

#define RF_DR_1M	0
#define RF_DR_2M	1
#define RF_DR_250K	2

#define	RF_PW_L0	0
#define RF_PW_L1	1
#define RF_PW_L2	2
#define RF_PW_L3	3

#define RF_PW_MIN	RF_PW_L0
#define RF_PW_MAX	RF_PW_L3

typedef enum {
	SYS_ROLE_PTX,
	SYS_ROLE_PRX,
} sys_role_t;

// PRX package format
//typedef struct {
//	uint8_t request;
//	uint8_t addrLsb;
//	uint8_t addrMsb;
//	uint8_t mark;
//	uint8_t value0;
//	uint8_t datlen;
//	uint8_t data[26];
//} prx_package_t;

// PRX package request
typedef enum {
	//	PRX_IO8_BIT = 0,
	//	PRX_IO8_RW,
	PRX_AVR_BIT = 0,
	PRX_AVR_RW,
	PRX_RF_BIT,
	PRX_RF_RW,
	PRX_WFLASH,
	PRX_RFLASH,
	PRX_RESET,
	PRX_ECHO,
} prx_request_t;

// 0 = everything is fine
// 1 = timeout
// 2 = no response from the remote device
#define RF_RET_PASS		0
#define RF_RET_TIMEOUT	1
#define RF_RET_PRXNRSP	2

#define WIRELESS_LOWLEVEL_INIT() \
	io_output_high(MOSI_PORT, MOSI_PIN);\
	io_output_high(NPCS_PORT, NPCS_PIN);\
	io_output_high(LED_PORT, LED_PIN);\
	io_output_low(SPCK_PORT, SPCK_PIN);\
	io_output_low(CE_PORT, CE_PIN);\
	io_input_hiz(MISO_PORT, MISO_PIN);\
	io_input_hiz(IRQ_PORT, IRQ_PIN)

int wirelessRead(char *buffer, int len);
int wirelessReadCount(void);
sys_role_t getRFSystemRole(void);
int wirelessInit(int rfChannel, sys_role_t sysRole, int rfDataRate, int rfPowerLevel, char rfAddress[5]);
int wirelessWriteSync(const char prxSerialNumber[6], const char *buffer, int len);
void wirelessWriteAsync(const char serialNumber[6], const char *data, int length);
//void wirelessWriteFIFO(const char *buf, int len);
//void wirelessWrite(const char *buffer, int bufferLength);
void wirelessWriteReg(uint8_t address, uint8_t value);
uint8_t wirelessReadReg(uint8_t address);
void setTxEndCallback(void *function);
void setRxEndCallback(void *function);
int isPRXResponse(void);
void writePRXAckPayload(const char *buffer, int length);


#endif /* WIRELESS_H_ */